package com.logistic.dao.impl;

import java.util.List;


import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.logistic.dao.HibernateSessionFactory;
import com.logistic.dao.ParaConfigDao;
import com.logistic.domain.ParaConfig;

public class ParaConfigDaoImpl extends HibernateDaoSupport implements ParaConfigDao {
	
	public int modify(ParaConfig pc) {
		try
		{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			String sql = "update ParaConfig pc set ";
			if(pc.getExchange_rate() != null && !"".equals(pc.getExchange_rate())){
				sql = sql + "pc.exchange_rate='"+pc.getExchange_rate()+"', ";
			}
			if(pc.getUnit_price() != null && !"".equals(pc.getUnit_price())){
				sql = sql + "pc.unit_price='"+pc.getUnit_price()+"', ";
			}
			if(pc.getFirst_price() != null && !"".equals(pc.getFirst_price())){
				sql = sql + "pc.first_price='"+pc.getFirst_price()+"', ";
			}
			if(pc.getIntegral_ratio() != null && !"".equals(pc.getIntegral_ratio())){
				sql = sql + "pc.integral_ratio='"+pc.getIntegral_ratio()+"', ";
			}
			if(pc.getPresentIntegral() != null && !"".equals(pc.getPresentIntegral())){
				sql = sql + "pc.presentIntegral='"+pc.getPresentIntegral()+"', ";
			}
			if(pc.getPresentMoney() != null && !"".equals(pc.getPresentMoney())){
				sql = sql + "pc.presentMoney='"+pc.getPresentMoney()+"', ";
			}
			if(pc.getRecommendFlag() != null && !"".equals(pc.getRecommendFlag())){
				sql = sql + "pc.recommendFlag='"+pc.getIntegral_ratio()+"', ";
			}
			sql = (String)sql.subSequence(0, sql.length()-2);
			Query q = s.createQuery(sql
					+ " where pc.id=?"); 
			
			q.setParameter(0, pc.getId());
			
			q.executeUpdate();
			t.commit();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally
		{
			HibernateSessionFactory.closeSession();
			return 1;
		}
	}
	

	public ParaConfig getParaConfigById(ParaConfig pc){
		ParaConfig newPc = null;
		try
		{
		Session s = HibernateSessionFactory.getSession();
		Transaction t = s.beginTransaction();
		
		String hql = "from ParaConfig pc where pc.id =? and pc.usaWarehouse = ?";
		Query q = s.createQuery(hql);
		q.setParameter(0, pc.getId());
		q.setParameter(1, pc.getUsaWarehouse());
		List list = q.list();
		t.commit();
		if(list.isEmpty() || list.size()==0) {
			return null;
		}
		newPc = (ParaConfig)list.get(0);
		}catch(HibernateException e)
		{
			e.printStackTrace();
		}finally
		{
			HibernateSessionFactory.closeSession();
			return newPc;
		}
	}
	
}
